import React, { Component } from 'react';
import { Col, Row, Modal, message, Select } from 'antd';
import { connect } from 'dva';
import style from '../base.less';
import RadiosTable from '../components/radiosTable';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LayerModel from '../components/layerModel';
import { tirePressureOptions, airFuelTypeOptions, engineTypeOptions, loginTypeOptions, bluetoothModuleTypeOptions, isAllInOneMachineOptions } from './optionsList';

const mapStateToProps = (state: any) => {
  return {
    loading: state.loading.effects['vehicleModelQuery/getFetchPage'],
    searchTBox: state?.menu?.dicData,
  };
};

class index extends Component<any> {
  state = {
    seriesCode: '',
    leftList: [],
    rightList: [],
    // initSearchTBox: [],
    // searchTBox: [],
    // isTBoxVal: false,
    attribute: [],
    isEditType: false,
    brandOptions: [],
    defaultBrand: '',
    selectBrand: ''
  };
  tableRef = null;
  leftLayerRef = React.createRef();
  rightLayerRef = React.createRef();

  async componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res: any) => {
        this.setState({
          brandOptions: res?.data,
          defaultBrand: res?.data[0].brandCode,
          selectBrand: res?.data[0].brandCode
        });
        this.initData(res?.data[0].brandCode);
      }
    });
  }
  initData = async (value: any) => {
    // 获取左侧数据
    const res = await this.leftGetList(value);
    // 如果数据大于0
    this.setOneSelect(res);
  };
  setOneSelect = res => {
    if (res && res.length > 0) {
      const id = res[0].seriesCode;
      // 默认选中第一个
      this.tableRef?.setIndex(id);
      // 执行右侧数据
      this.rightGetList(id);
    }
  };
  // 左侧获取数据
  leftGetList = (value: any) => {
    const { dispatch } = this.props;
    const { selectBrand } = this.state;
    let brandId = '';
    if (value) {
      brandId = value;
    } else {
      brandId = selectBrand;
    }
    return new Promise(resolve => {
      dispatch({
        type: 'vehicleModelQuery/getData',
        payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId: brandId },
        callback: res => {
          this.setState({
            leftList: res.data,
          });
          resolve(res.data);
        },
      });
    });
  };
  // 右侧获取数据
  rightGetList = (id: string = '') => {
    let { seriesCode, selectBrand } = this.state;

    if (id) {
      this.setState({
        seriesCode: id,
      });
      seriesCode = id;
    }
    const brandId = selectBrand;
    const { dispatch } = this.props;
    dispatch({
      type: 'vehicleModelQuery/getFetchPage',
      payload: { url: '/msdevice/base/vehicle/type/list', seriesCode, brandId },
      callback: res => {
        this.setState({
          rightList: res.data,
        });
      },
    });
  };
  // 左侧删除
  leftDelete = (record: any, close: any) => {
    const { dispatch } = this.props;
    const { selectBrand } = this.state;
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/vehicle/series/delete/${record.sid}/${selectBrand}` },
      callback: res => {
        const { statusCode } = res;
        // 如果成功
        if (statusCode === '0') {
          // 刷新数据
          this.initData(selectBrand);
          // 提示
          message.success('删除成功');
        }
        // 关闭
        close();
      },
    });
  };
  // 右侧删除
  rightDelete = (record, close) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/msdevice/base/vehicle/type/delete/${record.sid}` },
      callback: res => {
        const { statusCode } = res;
        if (statusCode === '0') {
          // 刷新数据
          this.rightGetList();
          // 提示
          message.success('删除成功');
        }
        close();
      },
    });
  };

  leftOnchange = async (obj, close) => {
    // 提交
    const { dispatch } = this.props;
    const { sid, seriesCode, seriesName, saleName, userId } = obj;
    const { selectBrand } = this.state;
    const params = {
      seriesCode,
      seriesName,
      saleName,
      userId,
      brandId: selectBrand,
    };

    Object.assign(params, sid ? { sid } : {});
    const type = sid ? 'edit' : 'save';
    dispatch({
      type: 'vehicleModelQuery/postObjWithRes',
      payload: { url: `/msdevice/base/vehicle/series/${type}`, ...params },
      callback: async res => {
        // 关闭
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          const arr = await this.leftGetList();

          // 如果新增后只有一条数据的情况
          if (arr && arr.length === 1) {
            this.setOneSelect(arr);
          }
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
        }
      },
    });
  };

  rightOnchange = async (obj, close) => {
    // 提交
    const { dispatch } = this.props;
    const { selectBrand } = this.state;
    const {
      sid,
      seriesCode,
      typeCode,
      typeName,
      saleName,
      engineType,
      tboxType,
      optionCode,
      extcolCode,
      intcolCode,
      changeCode,
      airFuelType,
      tirePressure,
      checkVehicleActiveCfg,
      electricMileage,
      bluetoothModuleType,
      isAllInOneMachine,
      batteryRangeList,
    } = obj;
    const optionCodeObj = objCreate(optionCode);
    const extcolCodeObj = objCreate(extcolCode);
    const intcolCodeObj = objCreate(intcolCode);
    const changeCodeObj = objCreate(changeCode);
    const newTboxType = this.searchTBoxChange(tboxType);
    const params = {
      seriesCode,
      typeCode,
      typeName,
      saleName,
      engineType,
      bluetoothModuleType,
      isAllInOneMachine,
      // tboxType,
      // tboxTypeName: tboxType,
      ...newTboxType,
      optionCode: optionCodeObj?.key,
      optionName: optionCodeObj?.value,
      extcolCode: extcolCodeObj?.key,
      extcolName: extcolCodeObj?.value,
      intcolCode: intcolCodeObj?.key,
      intcolName: intcolCodeObj?.value,
      changeCode: changeCodeObj?.key,
      changeName: changeCodeObj?.value,
      airFuelType,
      tirePressure,
      checkVehicleActiveCfg,
      electricMileage: (engineType === 2 || engineType === 3 || engineType === 4) ? Number(electricMileage) : '',
      brandId: selectBrand,
      batteryRangeList
    };

    function objCreate(arr: string[] = []) {
      const listKey: string[] = [];
      const listName: string[] = [];
      arr.forEach(e => {
        const obj = JSON.parse(e || '{}');
        listKey.push(obj.key);
        listName.push(obj.value);
      });
      return {
        key: listKey.join(','),
        value: listName.join(','),
      };
    }

    Object.assign(params, sid ? { sid } : {});
    const type = sid ? 'edit' : 'save';
    dispatch({
      type: 'vehicleModelQuery/postObjWithRes',
      payload: { url: `/msdevice/base/vehicle/type/${type}`, ...params },
      callback: res => {
        // 关闭
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          this.rightGetList();
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
        }
      },
    });
  };

  getAttribute = (bool = false) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ability/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/msdevice/base/data/type/attribute/list' },
      callback: res => {
        const data = res.data;
        const objName = {
          optional_package: {
            key: 'optionCode',
            name: '选装包',
          },
          body_color: {
            key: 'extcolCode',
            name: '车身颜色',
          },
          change_package: {
            key: 'changeCode',
            name: '改装包',
          },
          interior_color: {
            key: 'intcolCode',
            name: '内饰颜色',
          },
        };
        const attribute = [];
        for (const key in data) {
          if (Object.prototype.hasOwnProperty.call(data, key)) {
            const list = Object.entries(data[key]);
            const options = list.map(e => ({
              value: JSON.stringify({ key: e[0], value: e[1] }),
              label: e[1],
            }));
            attribute.push({
              type: 'checkbox',
              formItem: {
                name: objName[key].key,
                label: objName[key].name,
              },
              label: { disabled: bool },
              options,
            });
          }
        }
        this.setState({ attribute, isEditType: bool });
      },
    });
  };
  searchTBoxChange(code: number = 0) {
    const { searchTBox } = this.props;
    const searchTBoxList = [];
    const obj = {};
    searchTBox.forEach(e => {
      if (e?.dictCode === 'tboxType') {
        const key = parseInt(e?.dictKey);
        const value = e?.dictValue;
        if (code && key === code) {
          Object.assign(obj, {
            tboxType: key,
            tboxTypeName: value,
          });
        }
        searchTBoxList.push({
          label: value,
          value: key,
        });
      }
    });

    return code ? obj : searchTBoxList;
  }

  onBrandSelect = (value: any) => {
    this.setState({
      selectBrand: value
    })
    this.leftGetList(value);
  }
  render() {
    const {
      leftList = [],
      rightList = [],
      // initSearchTBox,
      // searchTBox,
      // isTBoxVal,
      attribute,
      isEditType,
      brandOptions,
      defaultBrand,
    } = this.state;
    const options = brandOptions.map((item: any) => {
      return {
        label: item.brandName,
        value: item.brandCode
      }
    });
    const searchTBoxList = this.searchTBoxChange();

    // 左侧表格
    const tableLeftProps = {
      onRef: ref => {
        this.tableRef = ref;
      },
      scroll: { x: 300, y: 650 },
      menu: [
        {
          name: '编辑',
          auth: 'modelVehicleSeries_edit',
          onClick: (record: any) => {
            // 打开弹层传值
            this.leftLayerRef?.current?.setInitVal('编辑车系', {
              // sid: record.seriesCode,
              ...record,
            });
          },
        },
        {
          name: '删除',
          auth: 'modelVehicleSeries_delete',
          onClick: (record: any) => {
            let confirmLoading = false;
            Modal.confirm({
              title: '删除',
              content: (
                <>
                  <p>确定要删除当前车系吗？</p>
                </>
              ),
              wrapClassName: 'layer-model-box',
              icon: <ExclamationCircleOutlined />,
              onOk: close => {
                // 如果为重复点击
                if (confirmLoading) {
                  return false;
                }
                confirmLoading = true;
                // 点击删除请求接口
                this.leftDelete(record, close);
              },
            });
          },
        },
      ],
      columns: [
        {
          title: '车系名称',
          dataIndex: 'seriesName',
        },
        {
          title: '车系编码',
          dataIndex: 'seriesCode',
        },
        {
          title: '车系营销名称',
          dataIndex: 'saleName',
        },
      ],
      onRow: record => {
        // 执行右侧数据
        this.rightGetList(record.seriesCode);
      },
      keyName: 'seriesCode',
      list: leftList,
      title: {
        name: '车系',
        auth: 'modelVehicleSeries_add',
        onClick: () => {
          this.leftLayerRef?.current?.setInitVal('新增车系', {});
        },
      },
    };
    const layerLeftColumns = [
      {
        type: 'select',
        formItem: {
          name: 'brandId',
          label: '品牌',
          initialValue: this.state.selectBrand,
        },
        label: {
          disabled: true,
          placeholder: '请选择品牌',
        },
        options: options,
      },
      {
        type: 'input',
        formItem: {
          name: 'seriesName',
          label: '车系名称',
          rules: [{ required: true, message: '请输入车系名称' }],
        },
        label: {
          placeholder: '请输入车系名称',
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'seriesCode',
          label: '车系编码',
          rules: [{ required: true, message: '请输入车系编码' }],
        },
        label: {
          placeholder: '请输入车系编码',
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'saleName',
          label: '车系营销名称',
        },
        label: {
          placeholder: '请输入车系营销名称',
        },
      },
    ];

    // 右侧表格
    const tableRightProps = {
      scroll: { x: 300, y: 650 },
      menu: [
        {
          name: '查看',
          auth: 'modelVehicleSeries_show',
          onClick: (record: any) => {
            // 取值
            const { seriesCode } = this.state;
            // 跳转
            this.props?.history.push(
              `/baseData/vehicleModelQuery?seriesCode=${seriesCode}&typeName=${record.typeName || ''}&brandId=${record.brandId || ''}`,
            );
          },
        },
        {
          name: '编辑',
          auth: 'modelVehicleSeries_edit',
          onClick: async (record: any) => {
            this.getAttribute(true);
            // 取值
            const { seriesCode } = this.state;
            const {
              optionCode,
              optionName,
              extcolCode,
              extcolName,
              intcolCode,
              intcolName,
              changeCode,
              changeName,
            } = record;
            const obj = {
              optionCode: createArr(optionCode, optionName),
              extcolCode: createArr(extcolCode, extcolName),
              intcolCode: createArr(intcolCode, intcolName),
              changeCode: createArr(changeCode, changeName),
            };
            // 打开弹层传值
            this.rightLayerRef?.current?.setInitVal('编辑车型', {
              ...record,
              ...obj,
              seriesCode,
              // sid: seriesCode,
            });

            function createArr(name: string, name2: string): string[] {
              const arr = (name || '').split(',');
              const list = (name2 || '').split(',');
              const newArr: string[] = [];
              arr.forEach((el: string, i: number) => {
                newArr.push(JSON.stringify({ key: el, value: list[i] }));
              });
              return newArr;
            }
          },
        },
        {
          name: '删除',
          auth: 'modelVehicleSeries_delete',
          onClick: (record: any) => {
            let confirmLoading = false;
            Modal.confirm({
              title: '删除',
              content: (
                <>
                  <p>确定要删除当前车型吗？</p>
                </>
              ),
              wrapClassName: 'layer-model-box',
              icon: <ExclamationCircleOutlined />,
              onOk: async close => {
                // 如果为重复点击
                if (confirmLoading) {
                  return false;
                }
                confirmLoading = true;
                // 点击删除请求接口
                await this.rightDelete(record, close);
              },
            });
          },
        },
      ],
      columns: [
        {
          title: '车型名称',
          dataIndex: 'typeName',
        },
        {
          title: '车型编码',
          dataIndex: 'typeCode',
        },
        {
          title: '车型营销名称',
          dataIndex: 'saleName',
        },
      ],
      keyName: 'typeCode',
      list: rightList,
      title: {
        name: '车型',
        // auth: 'modelVehicleSeries_add',
        auth: false,
        onClick: () => {
          const { seriesCode } = this.state;
          this.getAttribute();
          this.rightLayerRef?.current?.setInitVal('新增车型', { seriesCode });
        },
      },
    };
    const layerRightColumns = [
      {
        type: 'select',
        formItem: {
          name: 'brandId',
          label: '品牌',
          initialValue: this.state.selectBrand,
        },
        label: {
          disabled: true,
          placeholder: '请选择品牌',
        },
        options: options,
      },
      {
        type: 'input',
        formItem: {
          name: 'typeName',
          label: '车型名称',
          rules: [{ required: true, message: '请输入车型名称' }],
        },
        label: {
          placeholder: '请输入车型名称',
          disabled: isEditType,
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'typeCode',
          label: '车型编码',
          rules: [{ required: true, message: '请输入车型编码' }],
          extra: '请输入不包含选装包、车身颜色、内饰颜色、改装包的其他几位编码',
        },
        label: {
          placeholder: '请输入车型编码',
          disabled: isEditType,
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'saleName',
          label: '车型营销名称',
        },
        label: {
          placeholder: '请输入车型营销名称',
          disabled: isEditType,
        },
      },
      {
        type: 'selectForDisplay',
        formItem: {
          name: 'engineType',
          label: '车型类别',
        },
        label: {
          placeholder: '请选择车型类别',
        },
        options: engineTypeOptions,
      },
      {
        type: 'inputForDisplay',
        formItem: {
          name: 'electricMileage',
          label: '纯电续航里程',
          rules: [{ required: true, message: '请填写纯电续航里程！' }],
        },
        label: {
          placeholder: '请输入纯电续航里程',
        },
      }, {
        type: 'inputNumberForDisplay',
        formItem: {
          name: 'batteryRangeList',
          label: 'SOC值设置',
          rules: [{ required: true, message: '电量值不可为空' }],
        },
      },
      {
        type: 'select',
        formItem: {
          name: 'tboxType',
          label: 'tbox类型',
        },
        label: {
          placeholder: '请选择tbox类型',
          showSearch: true,
          filterOption: (input, option) => (option?.dictValue || '').includes(input),
          // fieldNames: {
          //   label: 'dictValue',
          //   value: 'dictKey',
          // },
        },
        options: searchTBoxList,
      },
      {
        type: 'select',
        formItem: {
          name: 'airFuelType',
          label: '空调类型',
        },
        label: {
          placeholder: '请选择空调类型',
        },
        options: airFuelTypeOptions,
      },
      {
        type: 'select',
        formItem: {
          name: 'tirePressure',
          label: '胎压类型',
        },
        label: {
          placeholder: '请选择胎压类型',
        },
        options: tirePressureOptions,
      },
      {
        type: 'radio',
        formItem: {
          name: 'checkVehicleActiveCfg',
          label: '校验激活登录',
          rules: [{ required: true, message: '请选择' }],
          extra: '说明：勾选校验，则非访客用户在车机未激活状态下无法登录，请根据车型实际需求勾选。',
        },
        label: {
          placeholder: '请选择校验激活登录',
        },
        options: loginTypeOptions,
      },
      {
        type: 'radio',
        formItem: {
          name: 'bluetoothModuleType',
          label: '蓝牙模块类型',
          rules: [{ required: true, message: '请选择' }],
        },
        label: {
          placeholder: '请选择蓝牙模块类型',
        },
        options: bluetoothModuleTypeOptions,
      },
      {
        type: 'radio',
        formItem: {
          name: 'isAllInOneMachine',
          label: '是否一体机',
          rules: [{ required: true, message: '请选择' }],
        },
        label: {
          placeholder: '请选择是否一体机',
        },
        options: isAllInOneMachineOptions,
      },
      ...attribute,
    ];


    return (
      <div>
        <Row gutter={24}>
          <div style={{ margin: '0px 10px 10px 10px' }}>
            <div style={{ display: 'inline-block' }}>
              <span>品牌：</span>
            </div>
            <div style={{ display: 'inline-block' }}>
              <Select
                allowClear={false}
                placeholder="请选择品牌"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}

                onChange={this.onBrandSelect}
                style={{ width: '250px' }}
                key={defaultBrand}
                defaultValue={defaultBrand}
                options={options}
              >
              </Select>
            </div>
          </div>
        </Row>
        <Row gutter={24} className={style.baseData}>
          <Col span={12}>
            <RadiosTable {...tableLeftProps}></RadiosTable>
          </Col>
          {leftList && leftList.length > 0 ? (
            <Col span={12}>
              <RadiosTable {...tableRightProps}></RadiosTable>
            </Col>
          ) : (
            ''
          )}
        </Row>
        <LayerModel
          ref={this.leftLayerRef}
          onChange={this.leftOnchange}
          columns={layerLeftColumns}
        ></LayerModel>
        <LayerModel
          ref={this.rightLayerRef}
          onChange={this.rightOnchange}
          columns={layerRightColumns}
        ></LayerModel>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
